from flask import Blueprint,request,render_template,g,redirect,url_for
from .forms import QuestionForm,AnswerForm
from models import QuestionModel,AnswerModel
from exts import db
from decorators import login_required
from bs4 import BeautifulSoup
import base64,io

def convert_base64_to_image(base64_string):
    image_data = base64.b64decode(base64_string)
    return image_data

def extract_plain_text(html_content):
    # 将富文本内容解析为HTML文档
    soup = BeautifulSoup(html_content, 'html.parser')

    # 提取纯文本内容
    plain_text = soup.get_text()

    return plain_text

bp=Blueprint("qa",__name__,url_prefix="/")

@bp.route("/")
def index():
    questions=QuestionModel.query.order_by(QuestionModel.create_time.desc()).all()
    for question in questions:
        question.content=extract_plain_text(question.content)

    return render_template("index.html",questions=questions)

@bp.route("/qa/public",methods=['GET','POST'])
@login_required
def public_question():
    if request.method=='GET':
        form=QuestionForm()
        return render_template("public_question.html",form=form)
    else:
        form=QuestionForm(request.form)
        if form.validate():
            title=form.title.data
            content=form.content.data
            #uploadImage=form.uploadImage.data
            question=QuestionModel(title=title,content=content,author=g.user)
            db.session.add(question)
            db.session.commit()
            #todo:跳转到问答详情页
            from docx import Document,shared

            # 生成一个新的文档
            d = Document()

            # # 添加一个标题，做为一级标头
            # d.add_heading(f"表格 1", level=1)
            #
            # # 建一个5行5列的表格
            # table = d.add_table(rows=5, cols=5, style="Table Grid")
            #
            # # 往表格每一个表格中写入内容
            # for i in range(5):
            #     for j in range(5):
            #         table.cell(i, j).text = f"({i}-{j})"
            soup = BeautifulSoup(content, 'html.parser')
            for element in soup.descendants:
                if element.name == 'p':
                    d.add_paragraph(element.text)
                elif element.name == 'h1':
                    d.add_heading(element.text, level=1)
                elif element.name == 'table':
                    table = d.add_table(rows=0, cols=0)
                    for row in element.find_all('tr'):
                        table_row = table.add_row().cells
                        for cell in row.find_all(['td', 'th']):
                            table_row.append(cell.text)
                elif element.name == 'img':
                    base64_string=element.attrs['src'].split(',')[1]
                    # import re
                    #
                    # style = element.attrs['style']
                    # height = None
                    # width = None
                    #
                    # # 使用正则表达式匹配height和width的值
                    # height_match = re.search(r'height:\s*([\d.]+)', style)
                    # width_match = re.search(r'width:\s*([\d.]+)', style)
                    #
                    # # 提取height的值
                    # if height_match:
                    #     height = height_match.group(1)
                    #
                    # # 提取width的值
                    # if width_match:
                    #     width = width_match.group(1)
                    #
                    # print("Height:", height)
                    # print("Width:", width)
                    image = convert_base64_to_image(base64_string)
                    image_file = io.BytesIO(image)
                  #  from PIL import Image

                    # # 示例用法
                    # image_file.seek(0)  # 将文件指针移回文件开头
                    # image = Image.open(image_file)
                    # image.show()

                    # d.add_picture(image_file,width=shared.Pt(int(width)), height=shared.Pt(int(height)))
                    d.add_picture(image_file)
            # d.add_paragraph(content)
            # # 保存word到文件中
            d.save("test1.docx")

            return redirect("/")
        else:
            print(form.errors)
            return redirect(url_for("qa.public_question"))

@bp.route("/qa/detail/<qa_id>")
def qa_detail(qa_id):
    question=QuestionModel.query.get(qa_id)
    # return render_template("public_question.html", question=question)
    return render_template("detail.html",question=question)

#@bp.route("/answer/public",methods=['POST'])
@bp.post("/answer/public")
@login_required
def public_answer():
    form=AnswerForm(request.form)
    if form.validate():
        content=form.content.data
        question_id=form.question_id.data
        answer=AnswerModel(content=content,question_id=question_id,author_id=g.user.id)
        db.session.add(answer)
        db.session.commit()
        return redirect(url_for("qa.qa_detail",qa_id=question_id))
    else:
        print(form.errors)
        return redirect(url_for("qa.qa_detail",qa_id=request.form.get("question_id")))


@bp.route("/search")
def search():
    #/search?q=flask
    #/search/<q>
    #post,request.form
    q=request.args.get("q")
    questions=QuestionModel.query.filter(QuestionModel.title.contains(q)).all()
    return render_template("index.html",questions=questions)


#url传参
#邮件发送
#ajax
#jinja2
#orm与数据库
#cookie和session
#搜索
#前端
#部署
#flask全栈开发
#flask实战